import os
import re
import cv2
# from moviepy.editor import ImageClip, concatenate_videoclips

# 固定帧率
def img_to_video_fixed_framerate(folder_path, pattern, fps, size, name_out):
    # 获取文件夹内所有文件的列表
    file_list = os.listdir(folder_path)

    matching_files = [f for f in file_list if re.match(pattern, f)]
    matching_files.sort()

    # AVI格式编码输出 XVID
    four_cc = cv2.VideoWriter_fourcc(*'XVID')
    save_path = folder_path + '/../' + name_out 
    video_writer = cv2.VideoWriter(save_path, four_cc, float(fps), size, True)

    print(len(matching_files))

    # 按顺序将图片合成视频
    for file_name in matching_files:
        img=cv2.imread(folder_path+file_name, cv2.IMREAD_GRAYSCALE)
        img = cv2.equalizeHist(img)
        img = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
        video_writer.write(img)

    video_writer.release()
    cv2.destroyAllWindows()
    
#浮动帧率
def img_to_video_float_framerate(folder_path, pattern, name_out):
    file_list = os.listdir(folder_path)

    matching_files = [f for f in file_list if re.match(pattern, f)]
    matching_files.sort()
    
    num_total = len(matching_files)
    print(num_total)
    image_clips = []
    for i in range(num_total-1):
        idx_now = float(matching_files[i][:-4])
        idx_next = float(matching_files[i+1][:-4])
        # 定义图片与时间戳
        image_clips.extend([(matching_files[i],idx_next-idx_now)])  #图片+持续时间

    # 创建图片片段列表
    clips = []
    for filename, duration in image_clips:
        img = cv2.imread(folder_path+filename, cv2.IMREAD_GRAYSCALE)
        
        # #直方图均衡化，从红外滤光后的图像中提取明亮的部分
        img = cv2.equalizeHist(img)
        
        img_BGR = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
        clip = ImageClip(img).set_duration(duration)
        clips.append(clip)

    # 合成视频
    final_video = concatenate_videoclips(clips, method="compose")

    # 输出合成后的视频
    final_video.write_videofile(name_out, codec="libx264", audio_codec="aac")
                                       
if __name__ == '__main__':
    folder_path = 'bag/image_sf/'  # 文件夹路径
    prefix = ''  # 文件名前缀
    # 使用正则表达式匹配以指定前缀开头的文件名，并按数字进行排序
    pattern = re.compile(r'^{}\d+\.+\d+\.jpg$'.format(prefix))
    fps = 40
    size = (2448,2048)
    name_out = 'output_lf.avi'
    img_to_video_fixed_framerate(folder_path, pattern,fps, size, name_out)
